<?php
/**
 * Author: yixuan
 * Desc:
 * Time: 2016/7/26 18:08
 */

namespace app\model;

class Payment
{
    public static function unifiedorder($params, $wechat)
    {
        global $_G;
        //测试定义时间戳
//        $time = strtotime("+7 year +7 month +10 day");
        $time = TIMESTAMP;
        $data = [
            'appid' => $wechat['appid'],
            'mch_id' => $wechat['mchid'],
            'nonce_str' => random(8),
            'body' => mb_substr($params['title'], 0, 26),
            'attach' => $params['module_name'] . '-' . $params['themeid'] . '-' . $params['orderid'],
            'out_trade_no' => $params['uniontid'],
            'total_fee' => $params['fee'] * 100,
            'spbill_create_ip' => $_G['clientip'],
            'time_start' => date('YmdHis', $time),
            'time_expire' => date('YmdHis', $time + 600),
            'notify_url' => $_G['url_domain'] . 'payment/wechat/notify',
            'trade_type' => 'JSAPI',
            'openid' => $params['openid'],
        ];
        yxlog(['type' => '微信支付构造参数', 'data' => $data, 'wechat' => $wechat], '微信支付');
        if ($params['profit_sharing']) {
            $data['profit_sharing'] = $params['profit_sharing'];
        }
        $sign = self::makeSign($data, $wechat['signkey']);
        $data['sign'] = $sign;
        $url = 'https://api.mch.weixin.qq.com/pay/unifiedorder';
        $response = self::xmlCurl($url, to_xml($data));
        $result = xmlToArray($response);
        //判断返回状态码
        if ($result['return_code'] != 'SUCCESS') {
            return ['errcode' => 1, 'msg' => $result['return_msg']];
        }
        //判断业务状态码
        if ($result['result_code'] != 'SUCCESS') {
            return ['errcode' => 1, 'msg' => $result['err_code'] . ':' . $result['err_code_des']];
        }
        $return_data = [
            'appId' => $result['appid'],
            'timeStamp' => strval($time),
            'nonceStr' => $result['nonce_str'],
            'package' => 'prepay_id=' . $result['prepay_id'],
            'signType' => 'MD5',
        ];
        $return_data['paySign'] = self::makeSign($return_data, $wechat['signkey']);
        return ['errcode' => 0, 'msg' => 'success', 'data' => $return_data];
    }

    protected static function makeSign($data, $signkey)
    {
        $data = array_filter($data);
        ksort($data);
        $string = urldecode(http_build_query($data)) . '&key=' . $signkey;
        return strtoupper(md5($string));
    }

    protected static function xmlCurl($url, $xml)
    {
        $header[] = "Content-type: text/xml";      //定义content-type为xml,注意是数组
        $ch = curl_init($url);
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); // 兼容本地没有指定curl.cainfo路径的错误
        curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $xml);
        $response = curl_exec($ch);
        curl_close($ch);
        return $response;
    }
}